import os

from src.base.settings import Settings
from src.conf.base_conf import BaseConf
from src.conf.conf import Conf
from src.conf.backup import Backup
from src.conf.robot_conf import RobotConf
from src.conf.robot_cmd import RobotCmd
from src.conf.robot_regex import RobotRegex
from src.conf.timer_task import TimerTask


class ConfManager:
    def __init__(self):
        self.__work_path = Settings.WORK_PATH
        self.__main_dir = Settings.CONF_DIR
        self.__conf_name_list = ["配置.json", "备份.json", "机器人配置.json",
                                 "机器人命令.json", "机器人正则.json", "定时任务.json"]
        self.conf_path_list = [os.path.join(self.__work_path, self.__main_dir, path)
                               for path in self.__conf_name_list]
        # 文件夹不存在时自动生成
        if not os.path.exists(self.__main_dir):
            print("[DLS] 未检测到配置文件！将为你自动生成")
            os.mkdir(self.__main_dir)
        # 为配置类初始化
        self.conf = Conf(self.conf_path_list[0])
        self.backup = Backup(self.conf_path_list[1])
        self.robot_conf = RobotConf(self.conf_path_list[2])
        self.robot_cmd = RobotCmd(self.conf_path_list[3])
        self.robot_regex = RobotRegex(self.conf_path_list[4])
        self.timer_task = TimerTask(self.conf_path_list[5])
        # 建立映射关系
        self.conf_map: dict[str, BaseConf] = {
            "conf": self.conf,
            "backup": self.backup,
            "robot_conf": self.robot_conf,
            "robot_cmd": self.robot_cmd,
            "robot_regex": self.robot_regex,
            "timer_task": self.timer_task
        }

    def get_conf(self, conf_name="") -> dict:
        """获取配置文件内容(可指定名称)"""
        content = {}
        if conf_name:
            if self.conf_map.get(conf_name, ""):
                content[conf_name] = self.conf_map[conf_name].get_dict()
        else:
            for name in self.conf_map:
                content[name] = self.conf_map[name].get_dict()
        return content

    def update_conf(self, conf_dict=None):
        """从dict加载配置文件(对应名称)"""
        if conf_dict is None:
            conf_dict = {}
        for name in conf_dict:
            if self.conf_map.get(name, ""):
                self.conf_map[name].update_from_dict(conf_dict[name])
                self.conf_map[name].save()

    def reload(self):
        """重新加载所有配置"""
        for name in self.conf_map:
            self.conf_map[name].reload()
        print("[DLS] 配置文件加载完成！")
